package lazada.d20210914.t1;

import java.util.Stack;

public class Main {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param army int整型一维数组
     * @return int整型一维数组
     */
    public int[] battle(int[] army) {
        if (army == null || army.length == 0) {
            return new int[0];
        }

        Stack<Integer> stack = new Stack<>();
        int k;
        for (int i = 0; i < army.length; i++) {
            if (army[i] > 0) {
                // 直接进栈
                stack.push(army[i]);
            } else {
                // 找正在向右的部队进行作战
                k = army[i];
                while (!stack.isEmpty() && stack.peek() > 0) {
                    int r = stack.peek() + k;
                    if (r > 0) {
                        k = 0;
                        break;
                    } else if (r < 0) {
                        stack.pop();
                    } else {
                        stack.pop();
                        k = 0;
                        break;
                    }
                }

                if (k != 0) stack.push(k);
            }
        }

        int[] ans = new int[stack.size()];
        k = stack.size() - 1;
        while (!stack.isEmpty()) {
            ans[k--] = stack.pop();
        }
        return ans;
    }
}
